import store from '@/store'
import router from '@/router'
import routers from '@/router/routers'
import { login, logout, getUserInfo, forgetPasswordSendMail, forgetPasswordByUpdate } from '@/api/admin/sysuser'

import { setStore, getStore, clearSessionStore } from "@/libs/cache";
import { setToken, getToken } from "@/libs/auth";

const TOKEN = 'token', USER = 'user', 
IS_ADMIN = 'is_admin', ROLES = 'roles', 
PERMISSIONS = 'permissions', 
PERMISSIONS_RELATION = 'permissions_relation', ACCESS = 'access';

export default {
    state: {
        token: getToken(),
        user: null,
        isAdmin: false,
        roles: [],
        permissions: [],
        access: []
    },

    getters: {
        user: state => state.user,
        isAdmin: state => state.isAdmin,
        roles: state => state.roles,
        permissions: state => state.permissions,
        access: state => state.access
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
            setToken(token)
        },
        SET_USER: (state, data) => {
            state.user = data
            setStore({ name: USER, content: data, type: 'session' })
        },
        SET_IS_ADMIN: (state, data) => {
            state.isAdmin = data
            setStore({ name: IS_ADMIN, content: data, type: 'session' })
        },
        SET_ROLES: (state, data) => {
            state.roles = (data == undefined ? [] : data)
            setStore({ name: ROLES, content: data, type: 'session' })
        },
        SET_ACCESS(state, access) {
            state.access = (access == undefined ? [] : access)
            setStore({ name: ACCESS, content: access, type: 'session' })
        },
    },

    actions: {

        /**
         * 用户登录
         * @param commit
         * @param state
         * @param data {accout, password}
         * @returns {Promise<any>}
         * @constructor
         */
        async handleLogin({ commit, state }, data) {
            return await new Promise((resolve, reject) => {
                return login(data).then(res => {
                    if(res) {
                        if (res.token != undefined && res.status) {
                            commit('SET_TOKEN', res.token)

                            // 返回数据到login.vue
                            resolve(res)
                            // 返回请求数据到then，下个异步请求。
                            return res;
                        } else {
                            reject({code: 500, status: false, msg: res.msg})
                            return res;
                        }
                    }
                }).then((res) => {
                    // 登录成功，请求登录用户的权限信息
                    if(res.status) {
                        getUserInfo({token: res.token}).then(resUser => {
                            let user = resUser.user
                            let roles = resUser.roles
                            let access = resUser.access
                            commit('SET_USER', user)
                            commit('SET_IS_ADMIN', user.superAdmin)
                            commit('SET_ROLES', roles)
                            commit('SET_ACCESS', access)
                        })
                    }
                }).catch(() => {
                    reject({ status: 500, msg: '登录发生异常，请联系管理员' })
                })
            })
        },

        /**
         * 找回密码，发送邮件
         * @param {*} param0 
         * @param {*} data 
         */
        handleForgetPasswordSendMail({ commit, state }, data) {
            return new Promise((resolve, reject) => {
                forgetPasswordSendMail(data).then(response => {
                    resolve(response)
                }).catch(() => {
                    reject({ status: 500, msg: '申请密码找回异常' })
                })
            })
        },
        
        /**
         * 找回密码，重置密码
         * @param {*} param0 
         * @param {*} data 
         */
        handleForgetPasswordByUpdate({ commit, state }, data) {
            return new Promise((resolve, reject) => {
                forgetPasswordByUpdate(data).then(response => {
                    resolve(response)
                }).catch(() => {
                    reject({ status: 500, msg: '重置密码异常' })
                })
            })
        },

        /**
         * 用户刷新了页面，vuex中保存的数据丢失，需重新设置上去
         * @param commit
         * @param state
         * @param dispatch
         * @param data
         * @returns {Promise<any>}
         * @constructor
         */
        SetUserData({ commit, state, dispatch }, data) {
            return new Promise((resolve, reject) => {
                const user = getStore({name: USER})
                const isAdmin = getStore({name: IS_ADMIN})
                const roles = getStore({name: ROLES})
                const access = getStore({name: ACCESS})

                commit('SET_USER', user)
                commit('SET_IS_ADMIN', isAdmin)
                commit('SET_ROLES', roles)
                commit('SET_ACCESS', access)
                
                resolve()
            });
        },

        // 后端登出
        LogOut({ commit, state, dispatch }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    dispatch('FedLogOut').then(() => {})
                    resolve()
                }).catch(() => {
                    reject()
                })
            })
        },

        // 前端登出
        FedLogOut({ commit, state }, data) {
            return new Promise((resolve, reject) => {
                clearSessionStore()
                if(data) {
                    // 缓存登录超时退出的URL和参数，登录成功后返回原页面
                    setStore({ name: 'BACKURL', content: {url: data.url, query: data.query}, type: 'session' })
                }
                resolve()
            })
        }
    }
}